#include "permissionutils.h"

#include <stdlib.h>
#include <stdio.h>

#include <fcntl.h>

static void setPermission(Permission *perm, bool isread, bool iswrite, bool isexec) {
    perm->isRead = isread;
    perm->isWrite = iswrite;
    perm->isExecute = isexec;
}

bool initPermission(const char *path, Permission *perm) {
    if (!FileExists(path)) return false;

    lstat(path, &perm->st);
    
    setPermission(perm,
            ((S_IRUSR & perm->st.st_mode) != 0), 
            ((S_IWUSR & perm->st.st_mode) != 0), 
            ((S_IXUSR & perm->st.st_mode) != 0));

    return true;
}

bool isReadPermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm))
        return perm.isRead;
    else
        return false;
}
bool isWritePermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm))
        return perm.isWrite;
    else
        return false;
}
bool isExecutePermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm))
        return perm.isExecute;
    else
        return false;
}

bool setReadPermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm)) {
        chmod(path, perm.st.st_mode | S_IRUSR);
        return true;
    }
    else
        return false;
}
bool setWritePermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm)) {
        chmod(path, perm.st.st_mode | S_IWUSR);
        return true;
    }
    else
        return false;
}
bool setExecutePermission(const char *path) {
    Permission perm = {0};
    if (initPermission(path, &perm)) {
        chmod(path, perm.st.st_mode | S_IXUSR);
        return true;
    }
    else
        return false;
}

bool permissionToString(const Permission perm, char *buffer) {
    if (isNull(buffer)) return false;
    
    sprintf(buffer, "%s%s%s",  perm.isRead?"r":"-",
                                perm.isWrite?"w":"-",
                                perm.isExecute?"x":"-");
    return true;
}

bool permissionToStringWithPath(const char *path, char *buffer) {
    Permission perm = {0};
    if (initPermission(path, &perm)) {
        return permissionToString(perm, buffer);
    }
    return false;
}